package com.suning.sawp.web.controller;

import java.security.Principal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.suning.framework.page.QueryResult;
import com.suning.sawp.constants.ErrorCodeConstants;
import com.suning.sawp.constants.LoggerConstants;
import com.suning.sawp.dto.common.MyQueryParam;
import com.suning.sawp.dto.common.ReturnMsg;
import com.suning.sawp.dto.esb.LocateMemberInfo;
import com.suning.sawp.intf.esb.MemberInfoService;
import com.suning.sawp.intf.vguide.VGuideService;
import com.suning.sawp.po.vguide.VGuideRecord;
import com.suning.sawp.service.util.DJStringUtils;
import com.suning.sawp.service.util.DateUtils;
import com.suning.sawp.web.exception.MobileException;
import com.suning.sawp.web.exception.MyGsonView;

/**
 * 
 * V导购相关功能controller<br>
 * 〈功能详细描述〉
 *
 * @author Wuxiao
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Controller
@RequestMapping("/vguide")
public class VGuideController extends DjBaseController {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(LoggerConstants.SAWP_SERVICE);

	@Autowired
	VGuideService vGuideService;

	@Autowired
	MemberInfoService memberInfoService;

	/**
	 * 
	 * 功能描述:增加V导购记录 <br>
	 * 〈功能详细描述〉
	 *
	 * @param telNo
	 * @return
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	@RequestMapping("/addRecord.do")
	@ResponseBody
	public String addGuideRecord(String telNo, String storeCode,
			Principal principal) {
		GsonBuilder gsonbulid = new GsonBuilder().disableHtmlEscaping();
		Gson gson = gsonbulid.create();
		@SuppressWarnings("rawtypes")
		ReturnMsg ret = new ReturnMsg();
		try {
			ret = vGuideService.addGuideRecord(telNo, principal.getName(),
					storeCode);
		} catch (Exception e) {
			LOGGER.error("V导购记录录入异常", e);
			ret.setErrorCode(ErrorCodeConstants.VGUIDE_ERR_E001);
			ret.setErrorMessage(ErrorCodeConstants.VGUIDE_ERR_MAP
					.get(ErrorCodeConstants.VGUIDE_ERR_E001));
		}
		return gson.toJson(ret);
	}

	/**
	 * 
	 * 功能描述:增加V导购记录 <br>
	 * 〈功能详细描述〉
	 *
	 * @param telNo
	 * @return
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	@RequestMapping(value = "/queryRecord.do")
	public MyGsonView queryGuideRecordList(Principal principal, Integer pageSize,
			Integer currIndex) throws Exception {
		// 获取当前用户id，即工号
		String userId = principal.getName();

		LOGGER.debug("queryGuideRecordList, userId=" + userId + ", currIndex="
				+ currIndex + ", pageSize=" + pageSize);

		// 设置默认的页面大小和起始位置20,0
		Integer newPageSize = pageSize;
		if (null == newPageSize || newPageSize < 1) {
		    newPageSize = 20;
		}
		Integer newCurrIndex = currIndex;
		if (null == newCurrIndex || newCurrIndex < 0) {
		    newCurrIndex = 0;
		}

		// 构造分页查询参数
		MyQueryParam<String> param = new MyQueryParam<String>();
		param.setQueryParam(userId);
		param.setCurrIndex(newCurrIndex);
		param.setPageSize(newPageSize);

		// 调用业务接口查询业务数据列表分页信息
		QueryResult<VGuideRecord> result = null;
		try {
			// 调用业务接口查询业务数据列表分页信息
			result = vGuideService.queryGuideRecordList(param);
		} catch (Exception e) {
			LOGGER.warn("queryGuideRecordList failed", e);
			// 接口调用异常，定义异常码，抛出异常
			String errCode = ErrorCodeConstants.ERR_0002;
			throw new MobileException(errCode,
					ErrorCodeConstants.ERR_MAP.get(errCode));
		}

		// 定义数据列表
		List<Map<String, String>> recordList = null;
		if (result != null && null != result.getDatas()) {
			// 获取当前页数据
			recordList = new ArrayList<Map<String, String>>();
			Map<String, String> rtn = null;

			for (VGuideRecord record : result.getDatas()) {
				rtn = new HashMap<String, String>();

				// 会员画像url,需要通过手机号获取会员编码
				String memberProtraitUrl = DJStringUtils.getMemberProtraitUrl(getCustNo(record
						.getTelNo()));
				rtn.put("memberPortraitUrl", memberProtraitUrl);

				rtn.put("mobile", DJStringUtils.sensitiveHandleEx(
						record.getTelNo(), 3, 2));
				rtn.put("recordTime", DateUtils.getDateStrByFormat(
						record.getCreateTime(), null));
				recordList.add(rtn);
			}
		}

		// 转换实体为json字符串返回
		MyGsonView view = createGsonView();
		view.addStaticAttribute("data", recordList);
		return view;
	}

	/**
	 * 根据手机号码查询会员编码
	 * 
	 * @param telNo
	 * @return
	 */
	private String getCustNo(String telNo) {
		// 调用会员接口查询会员编码
		LocateMemberInfo memberInfo = memberInfoService
				.locateMemberByMobileNo(telNo);

		String custNo = "";
		if ((memberInfo != null)
				&& (StringUtils.isBlank(memberInfo.getCustNum()))) {
			custNo = memberInfo.getCustNum();
		}
		return custNo;
	}

}
